package com.crm.service;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.crm.dao.BuyDAO;
import com.crm.po.Buy;
import com.crm.util.DateEx;
import com.crm.util.ExcelEx;
import com.crm.util.MathEx;
import com.crm.util.RequestEx;
import com.crm.util.StringEx;
import com.crm.vo.Excel;

public class BuyService {
	
	private static Logger logger = Logger.getLogger(BuyService.class);
	
	public Map<String, Object> getBuys(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from Buy t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行
		
		String username = RequestEx.getCurUser(request).getUsername();
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String goods = RequestEx.getStringTrim(request.getParameter("goods"));
		String buycompany = RequestEx.getStringTrim(request.getParameter("buycompany"));
		String buyer = RequestEx.getStringTrim(request.getParameter("buyer"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(username != null && username.trim().length() > 0 && !username.equalsIgnoreCase("admin")){
			Hql.append(" and t.buyer = '");
			Hql.append(username);
			Hql.append("' ");
		}
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(goods != null && goods.trim().length() > 0){
			Hql.append(" and t.goods like '%");
			Hql.append(goods);
			Hql.append("%' ");
		}
		if(buycompany != null && buycompany.trim().length() > 0){
			Hql.append(" and t.buycompany like '%");
			Hql.append(buycompany);
			Hql.append("%' ");
		}
		if(buyer != null && buyer.trim().length() > 0){
			Hql.append(" and t.buyer like '%");
			Hql.append(buyer);
			Hql.append("%' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() == 0){
			Hql.append(" and t.buydate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '9999-12-31' ");
		}
		if(fromDate.trim().length() == 0 && toDate.trim().length() > 0){
			Hql.append(" and t.buydate BETWEEN '1970-01-01' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() > 0){
			Hql.append(" and t.buydate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		
		BuyDAO dao = new BuyDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.buydate desc, t.creattime desc ");
	    List<Buy> list = dao.buyListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    
	    return map;
	} 
	
	public int getBuyCountByTreeid(String treeid, String islive){
		StringBuffer Hql = new StringBuffer(" from Buy t where 1=1 ");

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		
		BuyDAO dao = new BuyDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
	    
	    return count;
	} 
	
	public boolean saveOrUpdateBuy(HttpServletRequest request){
		try{
			
			String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
			
			String tid = RequestEx.getStringTrim(request.getParameter("tid"));
			Date buydate = RequestEx.getSqlDate(request.getParameter("buydate"));
			String goods = RequestEx.getStringTrim(request.getParameter("goods"));
			Double price = RequestEx.getDouble(request.getParameter("price"));
			Double amount = RequestEx.getDouble(request.getParameter("amount"));
			Double totalprice = RequestEx.getDouble(request.getParameter("totalprice"));
			String buycompany = RequestEx.getStringTrim(request.getParameter("buycompany"));
			String supplier = RequestEx.getStringTrim(request.getParameter("supplier"));
			String tel = RequestEx.getStringTrim(request.getParameter("tel"));
			String phone = RequestEx.getStringTrim(request.getParameter("phone"));
			String address = RequestEx.getStringTrim(request.getParameter("address"));
			String remark = RequestEx.getStringTrim(request.getParameter("remark"));
			
			BuyDAO dao = new BuyDAO();
			Buy buy = null;
			if(tid != null && tid.trim().length() > 0){
				buy = dao.findById(tid);
			}else{				
				buy = new Buy();
				buy.setCreattime(DateEx.getCurDatetimeAsLong());
				buy.setCreater(RequestEx.getCurUser(request).getUsername());
				buy.setBuyer(RequestEx.getCurUser(request).getUsername());
			}
			buy.setBuydate(buydate);
			buy.setGoods(goods);
			buy.setPrice(price);
			buy.setAmount(amount);
			buy.setTotalprice(totalprice);
			buy.setBuycompany(buycompany);
			buy.setSupplier(supplier);
			buy.setTel(tel);
			buy.setPhone(phone);
			buy.setAddress(address);

			buy.setCGroup(treeid);
			buy.setRemark(remark);
			buy.setIslive("Y");
			
			buy.setUpdatetime(DateEx.getCurDatetimeAsLong());
			buy.setUpdater(RequestEx.getCurUser(request).getUsername());
			
			dao.saveOrUpdate(buy);
		}catch(Exception e){
			logger.error("save or update buy fail:", e);
			return false;
		}
	    return true;
	}
	
	public boolean deleteBuys(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Buy T SET T.islive = 'N' WHERE T.tid IN (" + tids + ")";
				BuyDAO dao = new BuyDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete buy fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean recoverBuys(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Buy T SET T.islive = 'Y' WHERE T.tid IN (" + tids + ")";
				BuyDAO dao = new BuyDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("recover buy fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean reallyDeleteBuys(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "DELETE FROM Buy T WHERE T.tid IN (" + tids + ")";
				BuyDAO dao = new BuyDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("really delete buy fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public double mathJJCC(HttpServletRequest request){
		int type = RequestEx.getInteger(request.getParameter("type"));
		Double number1 = RequestEx.getDouble(request.getParameter("n1"));
		Double number2 = RequestEx.getDouble(request.getParameter("n2"));
		
		return MathEx.mathJJCC(number1, number2, 2, type);
	}
	
	public String mathBatchAdd(HttpServletRequest request){			
		String amount_temp = RequestEx.getStringTrim(request.getParameter("amount_temp"));
		String price_temp = RequestEx.getStringTrim(request.getParameter("price_temp"));
		String totalprice_temp = RequestEx.getStringTrim(request.getParameter("totalprice_temp"));
		
		double amount_sum = MathEx.mathBatchAdd(amount_temp.split("_"), 2);
		double price_sum = MathEx.mathBatchAdd(price_temp.split("_"), 2);
		double totalprice_sum = MathEx.mathBatchAdd(totalprice_temp.split("_"), 2);
		
		StringBuffer buffer = new StringBuffer("");
		
		buffer.append("{\"amount_sum\":\"" + amount_sum + "\",");
		buffer.append("\"price_sum\":\"" + price_sum + "\",");
		buffer.append("\"totalprice_sum\":\"" + totalprice_sum + "\"}");

		return buffer.toString();
	}


	public void exportBuys(HttpServletRequest request, HttpServletResponse response){
		StringBuffer Hql = new StringBuffer(" from Buy t where 1=1 ");
		
		String username = RequestEx.getCurUser(request).getUsername();
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String tids = RequestEx.getStringTrim(request.getParameter("tids"));
		String goods = RequestEx.getStringTrim(request.getParameter("goods"));
		String buycompany = RequestEx.getStringTrim(request.getParameter("buycompany"));
		String buyer = RequestEx.getStringTrim(request.getParameter("buyer"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(username != null && username.trim().length() > 0 && !username.equalsIgnoreCase("admin")){
			Hql.append(" and t.buyer = '");
			Hql.append(username);
			Hql.append("' ");
		}
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(tids != null && tids.trim().length() > 0){
			Hql.append(" and t.tid in (");
			Hql.append(tids);
			Hql.append(") ");
		}
		if(goods != null && goods.trim().length() > 0){
			Hql.append(" and t.goods like '%");
			Hql.append(goods);
			Hql.append("%' ");
		}
		if(buycompany != null && buycompany.trim().length() > 0){
			Hql.append(" and t.buycompany like '%");
			Hql.append(buycompany);
			Hql.append("%' ");
		}
		if(buyer != null && buyer.trim().length() > 0){
			Hql.append(" and t.buyer like '%");
			Hql.append(buyer);
			Hql.append("%' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() == 0){
			Hql.append(" and t.buydate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '9999-12-31' ");
		}
		if(fromDate.trim().length() == 0 && toDate.trim().length() > 0){
			Hql.append(" and t.buydate BETWEEN '1970-01-01' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() > 0){
			Hql.append(" and t.buydate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		
		BuyDAO dao = new BuyDAO();
		Hql.append(" order by t.buydate desc ");
	    List<Buy> list = dao.buyList(Hql.toString());
	    
	    String[][] grids = new String[list.size() + 1][14];
	    String[] titles = {"日期", "采购物品", "单价", "数量", "合计金额", "购货公司", "供应商", "固定电话", "移动电话", "地址", "采购员", "备注", "创建时间", "修改时间"}; 
	    grids[0] = titles;
		for(int i = 0; i < list.size(); i ++){
			Buy buy = list.get(i);
			grids[i + 1][0] = StringEx.valueOf(buy.getBuydate(), StringEx.formatDate);
			grids[i + 1][1] = StringEx.valueOf(buy.getGoods());
			grids[i + 1][2] = StringEx.valueOf(buy.getPrice());
			grids[i + 1][3] = StringEx.valueOf(buy.getAmount());
			grids[i + 1][4] = StringEx.valueOf(buy.getTotalprice());
			grids[i + 1][5] = StringEx.valueOf(buy.getBuycompany());
			grids[i + 1][6] = StringEx.valueOf(buy.getSupplier());
			grids[i + 1][7] = StringEx.valueOf(buy.getTel());
			grids[i + 1][8] = StringEx.valueOf(buy.getPhone());
			grids[i + 1][9] = StringEx.valueOf(buy.getAddress());
			grids[i + 1][10] = StringEx.valueOf(buy.getBuyer());
			grids[i + 1][11] = StringEx.valueOf(buy.getRemark());
			grids[i + 1][12] = StringEx.valueOfLongDate(buy.getCreattime());
			grids[i + 1][13] = StringEx.valueOfLongDate(buy.getUpdatetime());
		}
	    ExcelEx.toExcel(request, response, new Excel("采购信息[导出时间" + DateEx.getCurDateTime() + "]", grids));
	} 
	
	public static void main(String[] args){

	}
	
}
